package Numpy;

public class PrintMatrixClockwise29 {
    public int[] spiralOrder(int[][] matrix) {
        int[] result = new int[matrix.length * matrix[0].length];
        int left = 0, right = matrix[0].length - 1;
        int up = 0, down = matrix.length - 1;
        int index = 0;
        while (index < matrix.length * matrix[0].length) {

            for (int j = left; j <= right; j++) {
                result[index++] = matrix[up][j];
            }
            up++;
            for (int i = up; i <= down; i++) {
                result[index++] = matrix[right][i];
            }
            right--;
            for (int j = right; j >= left; j--) {
                result[index++] = matrix[down][j];
            }
            down--;
            for (int i = down; i >= up; i--) {
                result[index++] = matrix[i][left];
            }
            left++;

        }
        return result;
    }
}
